package org.example.os.synchronous.producer_comsumer;

import java.util.LinkedList;

/**
 * synchronized + wait() / notifyAll()
 */
public class WaitNotifyAllAchievement {
    private final LinkedList<Integer> buffer = new LinkedList<>();
    private final int capacity;

    public WaitNotifyAllAchievement(int capacity) {
        this.capacity = capacity;
    }

    public void produce() throws InterruptedException {
        int value = 0;
        while (true) {
            synchronized (this) {
                while (buffer.size() == capacity) {
                    wait(); // 缓冲区满，等待
                }
                System.out.println("生产者生产: " + value);
                buffer.add(value++);
                notifyAll(); // 通知消费者
                Thread.sleep(1000);
            }
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            synchronized (this) {
                while (buffer.isEmpty()) {
                    wait(); // 缓冲区空，等待
                }
                int value = buffer.removeFirst();
                System.out.println("消费者消费: " + value);
                notifyAll(); // 通知生产者
                Thread.sleep(1000);
            }
        }
    }
}
